<template>
  <div class="pdf-analysis-container">
    <!-- 头部区域 -->
    <div class="header-section">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><Document /></el-icon>
            PDF文档智能分析
          </h2>
          <p class="page-subtitle">上传PDF文档，获取AI驱动的深度分析与见解</p>
        </div>
        <div class="stats-section">
          <el-statistic title="今日分析" :value="dailyAnalysis" />
          <el-statistic title="累计分析" :value="totalAnalysis" />
        </div>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧：上传和查询区域 -->
      <div class="left-panel">
        <!-- 上传区域 -->
        <el-card class="upload-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="card-icon"><Upload /></el-icon>
                <span>上传PDF文档</span>
              </div>
              <el-tag v-if="fileList.length" type="success" size="small">已选择文件</el-tag>
            </div>
          </template>

          <div class="upload-section">
            <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :on-change="handleFileChange"
                :show-file-list="false"
                accept=".pdf"
                :file-list="fileList"
                drag
            >
              <div class="upload-content">
                <div class="upload-icon-container">
                  <el-icon class="upload-icon" :size="48"><FolderOpened /></el-icon>
                  <div class="upload-text">
                    <p>拖拽PDF文件到此处或<em>点击上传</em></p>
                    <p class="el-upload__tip">支持PDF格式，单个文件不超过10MB</p>
                  </div>
                </div>
              </div>
            </el-upload>

            <!-- 文件信息 -->
            <div v-if="fileList.length" class="file-info">
              <div class="file-details">
                <el-icon><Document /></el-icon>
                <div class="file-text">
                  <p class="file-name">{{ fileList[0].name }}</p>
                  <p class="file-size">{{ formatFileSize(fileList[0].size) }}</p>
                </div>
                <el-button
                    type="danger"
                    text
                    :icon="Close"
                    @click="clearFile"
                    class="clear-btn"
                ></el-button>
              </div>
            </div>

            <el-button
                type="primary"
                @click="uploadPdf"
                :disabled="!fileList.length || isUploading || isQuerying"
                :loading="isUploading"
                class="upload-btn"
                :icon="UploadFilled"
                size="large"
            >
              {{ isUploading ? '上传中...' : '开始解析' }}
            </el-button>

            <!-- 上传状态提示 -->
            <el-alert
                v-if="uploadSuccess"
                title="上传成功！您可以开始提问了"
                type="success"
                :closable="true"
                @close="uploadSuccess = false"
                class="mt-4"
                show-icon
            />

            <el-alert
                v-if="uploadError"
                :title="uploadError"
                type="error"
                :closable="true"
                @close="uploadError = false"
                class="mt-4"
                show-icon
            />
          </div>
        </el-card>

        <!-- 查询区域 -->
        <el-card class="query-card" shadow="hover" :class="{ 'disabled-state': isUploading || !fileList.length }">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="card-icon"><ChatLineRound /></el-icon>
                <span>文档问答</span>
              </div>
              <el-tag v-if="questionHistory.length" type="info" size="small">
                已提问 {{ questionHistory.length }} 次
              </el-tag>
            </div>
          </template>

          <div class="query-section">
            <!-- 问题建议 -->
            <div v-if="suggestedQuestions.length && !question" class="suggested-questions">
              <p class="suggest-title">您可以尝试提问：</p>
              <div class="question-chips">
                <el-tag
                    v-for="(q, index) in suggestedQuestions"
                    :key="index"
                    class="question-chip"
                    @click="setQuestion(q)"
                >
                  {{ q }}
                </el-tag>
              </div>
            </div>

            <el-input
                v-model="question"
                placeholder="请输入关于文档的问题..."
                :disabled="isUploading || isQuerying || !fileList.length"
                class="query-input"
                size="large"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                resize="none"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>

            <div class="query-actions">
              <el-button
                  type="primary"
                  @click="queryPdf"
                  :disabled="!question.trim() || isUploading || isQuerying || !fileList.length"
                  :loading="isQuerying"
                  class="query-btn"
                  size="large"
              >
                <template #icon>
                  <el-icon><Promotion /></el-icon>
                </template>
                获取答案
              </el-button>

              <el-button
                  v-if="questionHistory.length > 0"
                  @click="showHistory"
                  :icon="Clock"
                  size="large"
              >
                历史记录
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 历史记录区域 -->
        <el-card class="history-card" shadow="hover" v-if="questionHistory.length > 0">
          <template #header>
            <div class="card-header">
              <el-icon class="card-icon"><Clock /></el-icon>
              <span>最近提问</span>
            </div>
          </template>

          <div class="history-list">
            <div
                v-for="(item, index) in questionHistory.slice(0, 3)"
                :key="index"
                class="history-item"
                @click="restoreQuestion(item.question)"
            >
              <div class="history-question">
                <el-icon><ChatDotRound /></el-icon>
                <span>{{ item.question }}</span>
              </div>
              <div class="history-time">{{ formatTime(item.time) }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧：结果展示区域 -->
      <div class="right-panel">
        <el-card class="result-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="card-icon"><Reading /></el-icon>
                <span>分析结果</span>
              </div>
              <div class="result-actions">
                <el-button
                    v-if="result.length > 0"
                    type="primary"
                    :icon="CopyDocument"
                    size="small"
                    @click="copyResult"
                >复制</el-button>
                <el-button
                    v-if="result.length > 0"
                    :icon="Download"
                    size="small"
                    @click="exportResult"
                >导出</el-button>
              </div>
            </div>
          </template>

          <div class="result-content">
            <!-- 空状态 -->
            <div v-if="!fileList.length" class="empty-state">
              <el-empty description="请先上传PDF文档" :image-size="120">
                <template #image>
                  <el-icon size="60" color="#C0C4CC"><Document /></el-icon>
                </template>
              </el-empty>
            </div>

            <!-- 等待上传状态 -->
            <div v-else-if="fileList.length && !uploadSuccess" class="waiting-state">
              <el-empty description="请先解析文档" :image-size="120">
                <template #image>
                  <el-icon size="60" color="#409EFF"><Upload /></el-icon>
                </template>
              </el-empty>
            </div>

            <!-- 加载状态 -->
            <div v-else-if="isQuerying" class="loading-indicator">
              <div class="loading-content">
                <el-progress type="circle" :percentage="70" :width="80" :show-text="false" indeterminate />
                <div class="loading-text">
                  <p class="loading-title">AI正在分析您的问题...</p>
                  <p class="loading-subtitle">这可能需要几秒钟时间</p>
                </div>
              </div>
            </div>

            <!-- 结果展示 -->
            <div v-else-if="result.length > 0" class="parsed-result-container">
              <div class="result-header">
                <div class="result-meta">
                  <el-tag type="info" size="small">回答长度: {{ result.length }} 字符</el-tag>
                  <el-tag type="info" size="small">生成时间: {{ generateTime }}秒</el-tag>
                </div>
              </div>

              <div v-html="result" class="parsed-result"></div>
            </div>

            <!-- 等待提问状态 -->
            <div v-else class="ready-state">
              <el-empty description="请输入问题开始分析" :image-size="120">
                <template #image>
                  <el-icon size="60" color="#67C23A"><ChatLineRound /></el-icon>
                </template>
                <template #description>
                  <p>文档已准备就绪，您可以提出相关问题</p>
                </template>
              </el-empty>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import {
  ElUpload, ElButton, ElIcon, ElAlert, ElInput, ElCard, ElProgress,
  ElStatistic, ElTag, ElEmpty, ElMessage
} from 'element-plus';
import {
  Loading, Document, Upload, FolderOpened, UploadFilled,
  ChatLineRound, Search, Reading, CopyDocument, Download,
  Close, Promotion, Clock, ChatDotRound
} from '@element-plus/icons-vue';
import axios from '../api/index.js';

export default {
  name: 'PdfAnalysis',
  computed: {
    Clock() {
      return Clock
    }
  },
  components: {
    ElUpload,
    ElButton,
    ElIcon,
    ElAlert,
    ElInput,
    ElCard,
    ElProgress,
    ElStatistic,
    ElTag,
    ElEmpty,
    Document,
    Upload,
    FolderOpened,
    UploadFilled,
    ChatLineRound,
    Search,
    Reading,
    CopyDocument,
    Download,
    Close,
    Promotion,
    Clock,
    ChatDotRound
  },
  setup() {
    // 状态管理
    const fileList = ref([]);
    const question = ref('');
    const result = ref('');
    const isUploading = ref(false);
    const isQuerying = ref(false);
    const uploadSuccess = ref(false);
    const uploadError = ref('');
    const partialResponse = ref('');
    const questionHistory = ref([]);
    const dailyAnalysis = ref(12);
    const totalAnalysis = ref(156);
    const generateTime = ref(0);
    const startTime = ref(null);

    // 建议的问题
    const suggestedQuestions = ref([
      "这篇文档的主要内容是什么？",
      "总结一下文档的关键点",
      "文档中提到了哪些重要数据？",
      "作者的主要观点是什么？"
    ]);

    // 计算属性
    const hasFile = computed(() => fileList.value.length > 0);
    const hasResult = computed(() => result.value.length > 0);

    // 处理文件选择
    const handleFileChange = (uploadFile) => {
      // 只保留最新选择的文件
      fileList.value = [uploadFile];
      // 重置之前的结果
      result.value = '';
      uploadSuccess.value = false;
      uploadError.value = '';
    };

    // 清除文件
    const clearFile = () => {
      fileList.value = [];
      result.value = '';
      uploadSuccess.value = false;
      uploadError.value = '';
      question.value = '';
    };

    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    // 格式化时间
    const formatTime = (timestamp) => {
      const date = new Date(timestamp);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    };

    // 设置问题
    const setQuestion = (q) => {
      question.value = q;
    };

    // 显示历史记录
    const showHistory = () => {
      // 可以扩展为显示完整历史记录的对话框
      ElMessage.info(`您有 ${questionHistory.value.length} 条提问记录`);
    };

    // 恢复问题
    const restoreQuestion = (q) => {
      question.value = q;
    };

    // 复制结果
    const copyResult = () => {
      // 实际实现需要使用navigator.clipboard API
      const textarea = document.createElement('textarea');
      textarea.value = result.value.replace(/<br>/g, '\n').replace(/<[^>]*>/g, '');
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      ElMessage.success('结果已复制到剪贴板');
    };

    // 导出结果
    const exportResult = () => {
      ElMessage.info('导出功能开发中');
    };

    // 上传PDF文件
    const uploadPdf = async () => {
      if (!fileList.value.length) return;

      const file = fileList.value[0].raw;
      if (!file) return;

      // 验证文件类型
      if (file.type !== 'application/pdf' && !file.name.endsWith('.pdf')) {
        uploadError.value = '请上传PDF格式的文件';
        return;
      }

      // 验证文件大小 (10MB)
      if (file.size > 10 * 1024 * 1024) {
        uploadError.value = '文件大小不能超过10MB';
        return;
      }

      try {
        isUploading.value = true;
        uploadError.value = '';
        uploadSuccess.value = false;

        const formData = new FormData();
        formData.append('file', file);

        // 调用上传接口
        const response = await axios.post('/ai/analysis/pdf/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        // 上传成功
        uploadSuccess.value = true;
        result.value = ''; // 清空之前的结果
        questionHistory.value = []; // 清空历史记录
      } catch (error) {
        console.error('PDF上传失败:', error);
        uploadError.value = error.response?.data?.message || '文件上传失败，请重试';
      } finally {
        isUploading.value = false;
      }
    };

    // 查询PDF解析结果
    const queryPdf = async () => {
      if (!question.value.trim()) return;

      try {
        isQuerying.value = true;
        result.value = '';
        partialResponse.value = '';
        startTime.value = new Date();

        // 记录问题历史
        questionHistory.value.unshift({
          question: question.value,
          time: new Date()
        });

        // 使用Fetch API处理流式响应
        const response = await fetch(axios.getUri() + '/ai/analysis/pdf/query', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('jwt'),
          },
          body: JSON.stringify({question: question.value})
        });

        if (!response.ok) {
          throw new Error('查询失败: ' + response.statusText);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');

        while (true) {
          const {done, value} = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');

          for (const line of lines) {
            if (line.startsWith('data:')) {
              const data = line.substring(5).trim();
              if (data) {
                partialResponse.value += data;
                // 实时更新结果展示
                result.value = partialResponse.value.replace(/\n/g, '<br>');
              }
            } else if (line.trim()) {
              partialResponse.value += line.trim();
              // 实时更新结果展示
              result.value = partialResponse.value.replace(/\n/g, '<br>');
            }
          }
        }

        // 流式输出完成，将完整响应设置到结果中
        result.value = partialResponse.value.replace(/\n/g, '<br>');

        // 计算生成时间
        const endTime = new Date();
        generateTime.value = ((endTime - startTime.value) / 1000).toFixed(1);
      } catch (error) {
        console.error('查询PDF失败:', error);
        result.value = `<span style="color: #f56c6c;">查询失败: ${error.message}</span>`;
      } finally {
        isQuerying.value = false;
        partialResponse.value = '';
      }
    };

    return {
      fileList,
      question,
      result,
      isUploading,
      isQuerying,
      uploadSuccess,
      uploadError,
      partialResponse,
      questionHistory,
      dailyAnalysis,
      totalAnalysis,
      generateTime,
      suggestedQuestions,
      hasFile,
      hasResult,
      handleFileChange,
      clearFile,
      formatFileSize,
      formatTime,
      setQuestion,
      showHistory,
      restoreQuestion,
      copyResult,
      exportResult,
      uploadPdf,
      queryPdf
    };
  }
};
</script>

<style scoped>
.pdf-analysis-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  padding: 16px;
  gap: 16px;
}

.header-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.title-icon {
  margin-right: 10px;
  color: #409EFF;
}

.page-subtitle {
  font-size: 14px;
  color: #87909c;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 16px;
  min-height: 0; /* 防止flex容器溢出 */
}

.left-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-width: 0; /* 防止flex容器溢出 */
}

.right-panel {
  width: 50%;
  min-width: 0; /* 防止flex容器溢出 */
}

.upload-card, .query-card, .result-card, .history-card {
  border-radius: 12px;
  border: none;
  height: 100%;
}

:deep(.el-card__header) {
  border-bottom: 1px solid #f0f3f8;
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
  color: #1f2f3d;
}

.card-icon {
  margin-right: 8px;
  color: #409EFF;
}

.upload-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  padding: 20px;
  border-radius: 8px;
  border: 2px dashed #c0c4cc;
  background-color: #fafbfc;
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-icon-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.upload-icon {
  color: #409EFF;
}

.upload-text {
  text-align: center;
}

:deep(.el-upload__text) {
  text-align: center;
}

:deep(.el-upload__text p) {
  margin: 4px 0;
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #87909c;
}

.file-info {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  background-color: #f9f9f9;
}

.file-details {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-text {
  flex: 1;
}

.file-name {
  font-weight: 500;
  margin: 0;
  font-size: 14px;
}

.file-size {
  font-size: 12px;
  color: #87909c;
  margin: 0;
}

.clear-btn {
  margin-left: auto;
}

.upload-btn {
  width: 100%;
  height: 40px;
  font-weight: 500;
}

.query-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.suggested-questions {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 12px;
}

.suggest-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.question-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.question-chip {
  cursor: pointer;
  transition: all 0.3s;
}

.question-chip:hover {
  background-color: #409EFF;
  color: white;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  padding-left: 38px;
}

:deep(.el-textarea .el-input__prefix) {
  top: 12px;
  left: 12px;
}

.query-actions {
  display: flex;
  gap: 12px;
}

.query-btn {
  flex: 1;
  height: 40px;
  font-weight: 500;
}

.history-card {
  max-height: 200px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.history-item:hover {
  background-color: #f5f7fa;
}

.history-question {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  flex: 1;
  overflow: hidden;
}

.history-question span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-time {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
}

.result-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-state, .waiting-state, .ready-state {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-indicator {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.loading-text {
  text-align: center;
}

.loading-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 4px 0;
}

.loading-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.parsed-result-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
  overflow: auto;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-meta {
  display: flex;
  gap: 8px;
}

.parsed-result {
  line-height: 1.6;
  padding: 8px 0;
  white-space: pre-wrap;
  flex: 1;
  overflow: auto;
}

.result-actions {
  display: flex;
  gap: 8px;
}

.disabled-state {
  opacity: 0.7;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    flex-direction: column;
  }

  .right-panel {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .pdf-analysis-container {
    padding: 12px;
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .stats-section {
    width: 100%;
    justify-content: space-around;
  }

  .query-actions {
    flex-direction: column;
  }

  .question-chips {
    flex-direction: column;
  }
}
</style>